package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.config.RedisUtils;
import com.yupi.springbootinit.config.WxOpenConfig;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.RedisConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.CosManager;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.dto.orders.OrdersAddRequest;
import com.yupi.springbootinit.model.dto.orders.OrdersUpdateRequest;
import com.yupi.springbootinit.model.dto.orders.TempOrdersUpdateRequest;
import com.yupi.springbootinit.model.dto.user.*;
import com.yupi.springbootinit.model.entity.Orders;
import com.yupi.springbootinit.model.entity.Teachers;
import com.yupi.springbootinit.model.entity.Temporaryorders;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.enums.RecommenTeacherEnum;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.*;

import java.io.File;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yupi.springbootinit.utils.ConstantPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;
import static com.yupi.springbootinit.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
//@CrossOrigin()
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private TeachersService teachersService;

    @Resource
    private TemporaryordersService temporaryordersService;

    @Resource
    private OrdersService ordersService;

    @Resource
    private WxOpenConfig wxOpenConfig;

    @Resource
    private CosManager cosManager;

    @Resource
    private FileService fileService;

    @Resource
    private RedisUtils redisUtils;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户登录（微信开放平台）
     */
    @GetMapping("/login/wx_open")
    public BaseResponse<LoginUserVO> userLoginByWxOpen(HttpServletRequest request, HttpServletResponse response,
                                                       @RequestParam("code") String code) {
        WxOAuth2AccessToken accessToken;
        try {
            WxMpService wxService = wxOpenConfig.getWxMpService();
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
            String unionId = userInfo.getUnionId();
            String mpOpenId = userInfo.getOpenid();
            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
            }
            return ResultUtils.success(userService.userLoginByMpOpen(userInfo, request));
        } catch (Exception e) {
            log.error("userLoginByWxOpen error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @PostMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        System.out.println(request);
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

//    /**
//     * 根据 id 获取用户（仅管理员）
//     *
//     * @param id
//     * @param request
//     * @return
//     */
//    @GetMapping("/get")
////    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User user = userService.getById(id);
//        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
//        return ResultUtils.success(user);
//    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     *
     * @param request
     * @return
     */
    @PostMapping("/get")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(@RequestBody UserIdRequest userIdRequest, HttpServletRequest request) {
        Long id = userIdRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }


    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                   HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
                                                       HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    @PostMapping("/updateUser")
    public BaseResponse<Integer> updateUserContent(@RequestBody User user, HttpServletRequest request) {
        // 校验参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    @GetMapping("/searchById")
    public BaseResponse<List<Teachers>> searchUsersById(long id, HttpServletRequest request) {
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (id >= 0) {
            queryWrapper.eq("id", id);
        }
        List<Teachers> userList = teachersService.list(queryWrapper);
        List<Teachers> list = userList.stream().map(user -> teachersService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(list);
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @param request
     * @return
     */
    @PostMapping("/deleteOrder")
    public BaseResponse<Boolean> deleteOrder(long orderId, HttpServletRequest request) {
        if (orderId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", orderId);
        Orders order = ordersService.getOne(queryWrapper);
        Long userId = loginUser.getId();
        Long orderUserId = order.getUserId();
        if (!userId.equals(orderUserId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        boolean b = ordersService.removeById(orderId);
        // TODO: 2024/12/27 补充删除订单后，全部临时订单要删除
        return ResultUtils.success(b);
    }

    @PostMapping("/updateTempOrder")
    public BaseResponse<Boolean> updateTempOrder(@RequestBody TempOrdersUpdateRequest ordersUpdateRequest, HttpServletRequest request) {
//        User loginUser = userService.getLoginUser(request);
//        User user = new User();
//        BeanUtils.copyProperties(userUpdateMyRequest, user);
//        user.setId(loginUser.getId());
//        boolean result = userService.updateById(user);
//        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
//        return ResultUtils.success(true);
        // 校验参数是否为空
        if (ordersUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Temporaryorders order = temporaryordersService.getById(ordersUpdateRequest.getOrderId());
        if (order==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"订单不存在");
        }
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Long orderUserId = order.getUserId();
        if (!userId.equals(orderUserId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Orders newOrder = new Orders();
        BeanUtils.copyProperties(ordersUpdateRequest, newOrder);
        newOrder.setUserId(userId);
        newOrder.setLastLessonCount(ordersUpdateRequest.getLessonCount());
        boolean result = ordersService.updateById(newOrder);
        return ResultUtils.success(result);
    }


    @PostMapping("/updateOrder")
    public BaseResponse<Boolean> updateOrder(@RequestBody OrdersUpdateRequest ordersUpdateRequest, HttpServletRequest request) {
        // 校验参数是否为空
        if (ordersUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders order = ordersService.getById(ordersUpdateRequest.getOrderId());
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Long orderUserId = order.getUserId();
        if (!userId.equals(orderUserId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Boolean result = ordersService.updateOrder(ordersUpdateRequest);
        return ResultUtils.success(result);
    }

    //订单列表
    @GetMapping("/myOrdersList")
    public BaseResponse<Page<Orders>> getMyOrdersList(long pageSize, long pageNum, HttpServletRequest request) {
        System.out.println("=1111：");
        User loginUser = userService.getLoginUser(request);
        System.out.println("22222222222：");

        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<Orders> ordersList = ordersService.list(queryWrapper);
        if (ordersList == null) {
            return ResultUtils.success(null);
        }
        int size = ordersList.size();
        // 创建分页对象
        Page<Orders> page = new Page<>(pageSize, pageNum);
        // 执行分页查询
        Page<Orders> ordersPage = ordersService.page(page, queryWrapper);
        return ResultUtils.success(ordersPage);
    }

    //订单详情
    @GetMapping("/getOneOrder")
    public BaseResponse<Orders> getOneOrder(@RequestBody UserIdRequest userIdRequest, HttpServletRequest request) {
        Long id = userIdRequest.getId();
        User loginUser = userService.getLoginUser(request);
        Orders order = ordersService.getById(id);
        if (!order.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(order);
    }

    //订单详情
    @PostMapping("/getMyOrders")
    public BaseResponse<List<Orders>> getMyOrders(HttpServletRequest request) {
        System.out.println("request是："+request);
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        System.out.println("state是："+userObj);
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<Orders> ordersList = ordersService.list(queryWrapper);
        if (ordersList == null) {
            return ResultUtils.success(null);
        }
        return ResultUtils.success(ordersList);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> userList = userService.searchUsersByTags(tagNameList);
        return ResultUtils.success(userList);
    }

    @GetMapping("/searchByTags")
    public BaseResponse<List<Teachers>> searchTeachersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<Teachers> userList = teachersService.searchUsersByTags(tagNameList);
        List<Teachers> result = userList;
        return ResultUtils.success(userList);
    }


    //推荐教师
    @GetMapping("/recommendByRate")
    public BaseResponse<Page<Teachers>> recommendTeacherByRate(long num, int rule, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String rules = rule==1?"Desc":"Asc";
        String redisKey = String.format(RedisConstant.REDIS_KEY_RECOMMEND, "RATE" + rules + loginUser.getId());
        Object recommendValues = redisUtils.get(redisKey);
        Page<Teachers> teachersPage = (Page<Teachers>) recommendValues;
        //有缓存直接取
        if (teachersPage != null) {
            return ResultUtils.success(teachersPage);
        }
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (rule == 1) {
            //降序
            queryWrapper.orderByDesc("overallRating");
        } else {
            //升序
            queryWrapper.orderByAsc("overallRating");
        }
        // 创建分页对象
        Page<Teachers> page = new Page<>(1, num);
        // 执行分页查询
        Page<Teachers> userPage = teachersService.page(page, queryWrapper);
        try {
            redisUtils.setex(redisKey, userPage, RedisConstant.REDIS_KEY_EXPIRES_ONE_MIN*10);
        } catch (Exception e) {
            log.error("redis推荐失败", e);
        }
        return ResultUtils.success(userPage);
    }


    //推荐教师
    @GetMapping("/recommendByOrder")
    public BaseResponse<Page<Teachers>> recommendTeacherByOrder(long num, int rule, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String redisKey = String.format(RedisConstant.REDIS_KEY_RECOMMEND, "ORDER" + loginUser.getId());
        Object recommendValues = redisUtils.get(redisKey);
        Page<Teachers> teachersPage = (Page<Teachers>) recommendValues;
        //有缓存直接取
        if (teachersPage != null) {
            return ResultUtils.success(teachersPage);
        }
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        if (rule == 1) {
            //降序
            queryWrapper.orderByDesc("ordersTime");
        } else {
            //升序
            queryWrapper.orderByAsc("ordersTime");
        }
        // 创建分页对象
        Page<Teachers> page = new Page<>(1, num);
        // 执行分页查询
        Page<Teachers> userPage = teachersService.page(page, queryWrapper);
        try {
            redisUtils.setex(redisKey, userPage, RedisConstant.REDIS_KEY_EXPIRES_ONE_MIN*10);
        } catch (Exception e) {
            log.error("redis推荐失败", e);
        }
        return ResultUtils.success(userPage);
    }

    @PostMapping("/addUserTags")
    public BaseResponse<Boolean> addUsersTags(@RequestParam(required = false) List<String> tagNameList,
                                              HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(loginUser, user);
        user.setId(loginUser.getId());
        // 将标签列表转换为 JSON 字符串
        Gson gson = new Gson();
        String tagsJson = gson.toJson(tagNameList);
        user.setTags(tagsJson);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<Teachers>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, user));
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match/value")
    public BaseResponse<List<Teachers>> matchUsersByValue(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsersByValue(num, user));
    }

    @PostMapping("/addFile")
    public BaseResponse<String> addFile(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        FileUploadBizEnum bizEnum = FileUploadBizEnum.getEnumByValue("order_question");
        String fileUrl = fileService.uploadFile(file,bizEnum,userId);
        return ResultUtils.success(fileUrl);
    }


    /**
     * 创建订单
     *
     * @param ordersAddRequest
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/addOrder")
    public BaseResponse<Long> addOrder(OrdersAddRequest ordersAddRequest,@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        if (ordersAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersAddRequest, order);
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        order.setUserId(userId);
        order.setTeacherId(0L);
        order.setLastLessonCount(ordersAddRequest.getLessonCount());
        FileUploadBizEnum bizEnum = FileUploadBizEnum.getEnumByValue("order_question");
        // 生成唯一的 orderId
//        Long orderId = UUID.randomUUID().getLeastSignificantBits();
//        order.setOrderId(orderId);
        //上传题目
        String fileUrl = "";
        if (file != null) {
            fileUrl = fileService.uploadFile(file,bizEnum,userId);
        }
        order.setQuestionFile(fileUrl);
        boolean result = ordersService.save(order);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newPostId = order.getOrderId();
        return ResultUtils.success(newPostId);
    }

    @GetMapping("/getTempOrderList")
    public BaseResponse<List<Temporaryorders>> getTempOrderList(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Temporaryorders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<Temporaryorders> tempOrderList = temporaryordersService.list(queryWrapper);
        if (tempOrderList == null) {
            return ResultUtils.success(null);
        }
        return ResultUtils.success(tempOrderList);
    }

    /**
     * 选择订单（通过一面）
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/selectOrder")
    public BaseResponse<String> selectOrder(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Temporaryorders tempOrder = temporaryordersService.getById(id);
        Long teacherId = tempOrder.getTeacherId();
        String answerDirectory = tempOrder.getAnswerDirectory();
        //如果已经是面试阶段的订单，则成交
        if (tempOrder.getOrderStatus().equals(1)) {
            Orders order = ordersService.getById(tempOrder.getOrderId());
            order.setTeacherId(teacherId);
            order.setOrderStatus(1);
            order.setAnswerDirectory(answerDirectory);
            //删除其他临时订单
            QueryWrapper<Temporaryorders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId", tempOrder.getOrderId());
            temporaryordersService.remove(queryWrapper);
            ordersService.updateById(order);
            return ResultUtils.success("恭喜您，订单已成交");
        } else {
            //如果是一面阶段的订单，则进入面试阶段
            tempOrder.setOrderStatus(1);
        }
        temporaryordersService.updateById(tempOrder);
        return ResultUtils.success("订单已通过一面，现在可以与对方进一步交流辣！");
    }


    /**
     * 删除临时订单
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/deleteTempOrder")
    public BaseResponse<Boolean> deleteTempOrder(long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.deleteTempOrder(id, loginUser);
        return ResultUtils.success(b);
    }

    /**
     * 评论评分
     *
     * @param id
     * @param rate
     * @param comment
     * @param request
     * @return
     */
    @PostMapping("/comment")
    public BaseResponse<Boolean> commentOrder(long id, int rate, String comment, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders order = ordersService.getById(id);
        //判断是否订单已完成
        Integer status = order.getOrderStatus();
        if (status != 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "订单未完成，无法评价");
        }
        order.setUserRating(rate);
        order.setUserComments(comment);
        boolean result = ordersService.updateById(order);
        Long teacherId = order.getTeacherId();
        Teachers teachers = teachersService.getById(teacherId);
        //更新教师的评分
        if (rate >= 0) {
            teachersService.updateRate(rate, teachers);
        }
        //更新教师评论
        if (comment != null) {
            teachersService.updateComment(teachers);
        }

        return ResultUtils.success(result);
    }

    /**
     * 完成订单
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/confirmOrder")
    public BaseResponse<Boolean> confirmOrder(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Orders order = ordersService.getById(id);
        //判断是否订单已完成
        Integer status = order.getOrderStatus();
        if (status == 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "订单已完成，无法开始订单任务");
        }
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.confirmOrder(id, loginUser));
    }

    /**
     * 上传头像
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/user_avatar")
    public BaseResponse<String> uploadAvatar(@RequestPart("file") MultipartFile multipartFile,
                                             UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(2);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            //保存头像
            String user_avatar = FileConstant.COS_HOST + filepath;
            loginUser.setUserAvatar(user_avatar);
            userService.updateById(loginUser);
            String avatar = loginUser.getUserAvatar();
            // 返回可访问地址
            return ResultUtils.success(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 上传题目
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/question")
    public BaseResponse<String> uploadQuestion(@RequestPart("file") MultipartFile multipartFile,
                                               UploadFileRequest uploadFileRequest, HttpServletRequest request, long orderId) {
        User loginUser = userService.getLoginUser(request);
        Long id = loginUser.getId();
        Orders order = ordersService.getById(orderId);
        if (!order.getUserId().equals(id)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不是该用户的订单");
        }
        fileService.uploadQuestion(multipartFile, uploadFileRequest, orderId);
        return ResultUtils.success("上传成功");
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }

    /**
     * 获取全部用户列表，删除的不要
     */
    @GetMapping("/getUser")
    public BaseResponse<List<User>> getUserList() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("isDelete", 1);
        List<User> userList = userService.list(queryWrapper);
        return ResultUtils.success(userList);
    }


}
